package com.easysettle

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.easysettle.databinding.ActivityAddProductBinding
import com.easysettle.model.Product
import com.easysettle.service.MainService
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

/**
 * 商品录入Activity
 * 用于添加新商品到系统
 */
class AddProductActivity : AppCompatActivity() {
    // ViewBinding实例
    private lateinit var binding: ActivityAddProductBinding
    // 主服务实例
    private lateinit var mainService: MainService
    // 选中的图片URI
    private var imageUri: Uri? = null
    // 临时图片文件路径
    private var currentPhotoPath: String? = null

    companion object {
        // 日志标签
        private const val TAG = "AddProductActivity"
        // 权限请求码
        private const val PERMISSION_STORAGE_REQUEST_CODE = 102
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化ViewBinding
        binding = ActivityAddProductBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 初始化主服务
        mainService = MainService(this)
        
        // 设置返回按钮点击事件
        binding.btnBack.setOnClickListener {
            finish()
        }
        
        // 设置选择图片按钮点击事件
        binding.btnSelectImage.setOnClickListener {
            showImagePickerOptions()
        }
        
        // 设置保存商品按钮点击事件
        binding.btnSaveProduct.setOnClickListener {
            saveProduct()
        }
        
        // 获取并显示下一个可用的商品ID
        val nextId = mainService.getNextAvailableId()
        binding.tvProductId.text = getString(R.string.col_id) + ": " + String.format("%03d", nextId.toIntOrNull() ?: 0)
    }

    /**
     * 显示图片选择选项（从相册选择或拍照）
     */
    private fun showImagePickerOptions() {
        val options = arrayOf("从相册选择", "拍照")
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("选择图片来源")
            .setItems(options) {
                _, which ->
                when (which) {
                    0 -> openGallery()
                    1 -> takePhoto()
                }
            }
            .show()
    }

    /**
     * 打开相册选择图片
     */
    private fun openGallery() {
        // 检查存储权限
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.TIRAMISU) {
            if (!mainService.hasPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
                requestPermissions(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSION_STORAGE_REQUEST_CODE)
                return
            }
        } else {
            if (!mainService.hasPermission(android.Manifest.permission.READ_MEDIA_IMAGES)) {
                requestPermissions(arrayOf(android.Manifest.permission.READ_MEDIA_IMAGES), PERMISSION_STORAGE_REQUEST_CODE)
                return
            }
        }
        
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        galleryLauncher.launch(intent)
    }

    /**
     * 拍照获取图片
     */
    private fun takePhoto() {
        // 检查相机权限
        if (!mainService.hasPermission(android.Manifest.permission.CAMERA)) {
            requestPermissions(arrayOf(android.Manifest.permission.CAMERA), MainService.PERMISSION_CAMERA_REQUEST_CODE)
            return
        }
        
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            takePictureIntent.resolveActivity(packageManager)?.also {
                val photoFile: File? = try {
                    createImageFile()
                } catch (ex: IOException) {
                    Log.e(TAG, "创建图片文件失败", ex)
                    Toast.makeText(this, "创建图片文件失败", Toast.LENGTH_SHORT).show()
                    null
                }
                photoFile?.also {
                    imageUri = FileProvider.getUriForFile(
                        this,
                        "com.easysettle.fileprovider",
                        it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                    cameraLauncher.launch(takePictureIntent)
                }
            }
        }
    }

    /**
     * 创建临时图片文件
     */
    @Throws(IOException::class)
    private fun createImageFile(): File {
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "JPEG_${timeStamp}_", /* 前缀 */
            ".jpg", /* 后缀 */
            storageDir /* 目录 */
        ).apply {
            currentPhotoPath = absolutePath
        }
    }

    /**
     * 保存商品信息
     */
    private fun saveProduct() {
        // 获取用户输入
        val productName = binding.etProductName.text.toString().trim()
        val priceText = binding.etProductPrice.text.toString().trim()
        val barcode = binding.etBarcode.text.toString().trim()
        
        // 验证输入
        if (productName.isEmpty()) {
            Toast.makeText(this, getString(R.string.error_product_name_empty), Toast.LENGTH_SHORT).show()
            return
        }
        
        val price = priceText.toDoubleOrNull()
        if (price == null || price < 0) {
            Toast.makeText(this, getString(R.string.error_product_price_invalid), Toast.LENGTH_SHORT).show()
            return
        }
        
        // 获取下一个可用的商品ID
        val productId = mainService.getNextAvailableId()
        
        // 保存图片并获取图片路径
        val imagePath = saveImageToStorage()
        
        // 创建商品对象
        val product = Product(productId, productName, price, barcode, imagePath)
        
        // 添加商品
        mainService.addProduct(product) {
            success ->
            runOnUiThread {
                if (success) {
                    Toast.makeText(this, getString(R.string.product_added_success), Toast.LENGTH_SHORT).show()
                    // 清空输入框
                    binding.etProductName.text?.clear()
                    binding.etProductPrice.text?.clear()
                    binding.etBarcode.text?.clear()
                    binding.ivProductImage.setImageResource(R.drawable.ic_product_placeholder)
                    imageUri = null
                    currentPhotoPath = null
                    
                    // 更新显示的商品ID
                    val nextId = mainService.getNextAvailableId()
                    binding.tvProductId.text = getString(R.string.col_id) + ": " + String.format("%03d", nextId.toIntOrNull() ?: 0)
                } else {
                    Toast.makeText(this, "添加商品失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 将选择的图片保存到应用内部存储
     */
    private fun saveImageToStorage(): String? {
        if (imageUri == null) return null
        
        try {
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
            val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val fileName = "product_$timeStamp.jpg"
            val file = File(filesDir, fileName)
            
            FileOutputStream(file).use {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, it)
            }
            
            return file.absolutePath
        } catch (e: Exception) {
            Log.e(TAG, "保存图片失败", e)
            Toast.makeText(this, "保存图片失败", Toast.LENGTH_SHORT).show()
            return null
        }
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == PERMISSION_STORAGE_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                openGallery()
            } else {
                Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show()
            }
        } else if (requestCode == MainService.PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                takePhoto()
            } else {
                Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 相册选择结果处理
    private val galleryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        result ->
        if (result.resultCode == Activity.RESULT_OK && result.data != null) {
            imageUri = result.data?.data
            binding.ivProductImage.setImageURI(imageUri)
            currentPhotoPath = null
        }
    }

    // 相机拍照结果处理
    private val cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        result ->
        if (result.resultCode == Activity.RESULT_OK) {
            binding.ivProductImage.setImageURI(imageUri)
        }
    }
}